package com.fatcat.easybuy.config;

import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Configuration
public class VXConfig {

    @Value("${wechat.pay.merchant-id}")
    private String merchantId;

    @Value("${wechat.pay.merchant-serial-number}")
    private String merchantSerialNumber;

    @Value("${wechat.pay.api-v3-key}")
    private String apiV3key;

    @Value("${wechat.pay.appid}")
    private String appid;

    @Value("${wechat.pay.notify-url}")
    private String notifyUrl;

    @Value("${wechat.pay.private-key-path}")
    private String privateKeyPath;

    private RSAAutoCertificateConfig config;

    @PostConstruct
    public void init() {
        try {
            // 加载私钥文件
            ClassPathResource resource = new ClassPathResource(privateKeyPath.replace("classpath:", ""));
            Path keyPath = Paths.get(resource.getURI());

            // 构建配置
            this.config = new RSAAutoCertificateConfig.Builder()
                    .merchantId(merchantId)
                    .privateKeyFromPath(keyPath.toString())
                    .merchantSerialNumber(merchantSerialNumber)
                    .apiV3Key(apiV3key)
                    .build();
        } catch (IOException e) {
            throw new RuntimeException("加载微信支付配置失败", e);
        }
    }

    public RSAAutoCertificateConfig getConfig() {
        return config;
    }

    public String getAppid() {
        return appid;
    }

    public String getMerchantId() {
        return merchantId;
    }

    public String getNotifyUrl() {
        return notifyUrl;
    }
}